<template>
  <view class="record-edit-page">
    <view class="page-header">
      <text class="page-title">编辑病例</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <scroll-view v-else class="form-content" scroll-y>
      <view class="form-card">
        <view class="card-header">
          <text class="card-title">基本信息（只读）</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">患者姓名</text>
            <text class="value">{{ originalData.patient_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">主治医师</text>
            <text class="value">{{ originalData.doctor_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">就诊日期</text>
            <text class="value">{{ formatDate(originalData.visit_date) }}</text>
          </view>
        </view>
      </view>
      
      <view class="form-card">
        <view class="card-header">
          <text class="card-title">诊断信息</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">症状描述</text>
          </view>
          <view class="textarea-wrapper">
            <textarea v-model="formData.symptoms" class="textarea" placeholder="请详细描述患者症状" maxlength="1000" />
          </view>
          
          <view class="form-item">
            <text class="label">诊断结果</text>
          </view>
          <view class="textarea-wrapper">
            <textarea v-model="formData.diagnosis" class="textarea" placeholder="请输入诊断结果" maxlength="1000" />
          </view>
          
          <view class="form-item">
            <text class="label">治疗方案</text>
          </view>
          <view class="textarea-wrapper">
            <textarea v-model="formData.treatment_plan" class="textarea" placeholder="请输入治疗方案" maxlength="1000" />
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">处方信息</text>
          <text class="card-subtitle">（可选）</text>
        </view>
        <view class="card-body">
          <view v-for="(item, index) in formData.prescription" :key="index" class="prescription-item">
            <view class="prescription-header">
              <text class="prescription-title">药品 {{ index + 1 }}</text>
              <text class="remove-btn" @click="removePrescription(index)">删除</text>
            </view>
            <view class="form-item">
              <text class="label">药品名称</text>
              <input v-model="item.medicine_name" class="input" placeholder="请输入药品名称" />
            </view>
            <view class="form-item">
              <text class="label">剂量</text>
              <input v-model="item.dosage" class="input" placeholder="例如：500mg" />
            </view>
            <view class="form-item">
              <text class="label">用药频率</text>
              <input v-model="item.frequency" class="input" placeholder="例如：每日3次" />
            </view>
            <view class="form-item">
              <text class="label">疗程</text>
              <input v-model="item.duration" class="input" placeholder="例如：7天" />
            </view>
          </view>
          <button class="btn-add" @click="addPrescription">+ 添加处方药品</button>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">检查结果</text>
          <text class="card-subtitle">（可选）</text>
        </view>
        <view class="card-body">
          <view v-for="(item, index) in formData.examination_results" :key="index" class="exam-item">
            <view class="exam-header">
              <text class="exam-title">检查 {{ index + 1 }}</text>
              <text class="remove-btn" @click="removeExam(index)">删除</text>
            </view>
            <view class="form-item">
              <text class="label">检查类型</text>
              <input v-model="item.exam_type" class="input" placeholder="例如：X光、CT等" />
            </view>
            <view class="form-item">
              <text class="label">检查结果</text>
              <input v-model="item.exam_result" class="input" placeholder="请输入检查结果" />
            </view>
            <view class="form-item">
              <text class="label">检查日期</text>
              <picker mode="date" :value="getExamDateStr(index)" @change="(e) => handleExamDateChange(e, index)">
                <view class="picker-input">{{ getExamDateStr(index) || '请选择日期' }}</view>
              </picker>
            </view>
            <!-- 检查结果图片 -->
            <view class="form-item">
              <text class="label">检查图像</text>
              <view class="image-preview-wrapper">
                <view v-if="item.images && item.images.length > 0" class="images-grid">
                  <view v-for="(img, imgIndex) in item.images" :key="imgIndex" class="image-item">
                    <image :src="getImageUrl(img)" mode="aspectFill" class="image" @click="previewExamImage(item.images, img, imgIndex)" />
                    <text class="remove-image-btn" @click="removeExamImage(index, imgIndex)">×</text>
                  </view>
                </view>
                <!-- 图片上传组件 -->
                <view class="image-upload-section">
                  <uni-file-picker 
                    :value="getExamImageFileList(index)"
                    file-mediatype="image"
                    mode="grid"
                    :limit="9"
                    :auto-upload="false"
                    @select="(e) => handleExamImageSelect(e, index)"
                    @delete="(e) => handleExamImageDelete(e, index)"
                  />
                  <text class="form-hint">可上传新的检查图像，最多9张</text>
                </view>
              </view>
            </view>
          </view>
          <button class="btn-add" @click="addExam">+ 添加检查记录</button>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">其他信息</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">协助护士</text>
            <view class="nurse-selector">
              <view v-if="selectedNurses.length > 0" class="selected-nurses">
                <view v-for="(nurse, idx) in selectedNurses" :key="nurse._id" class="nurse-tag">
                  <text class="nurse-name">{{ nurse.displayName }}</text>
                  <text class="remove-btn" @click="removeNurse(idx)">×</text>
                </view>
              </view>
              <picker mode="selector" :range="nurseOptions" :range-key="'displayName'" @change="handleNurseSelect">
                <view class="picker-input">添加护士</view>
              </picker>
            </view>
          </view>
          
          <view class="form-item">
            <text class="label">备注信息</text>
          </view>
          <view class="textarea-wrapper">
            <textarea v-model="formData.notes" class="textarea" placeholder="请输入备注信息（可选）" maxlength="500" />
          </view>
          
          <view class="form-item">
            <text class="label">病例状态</text>
            <picker mode="selector" :range="statusOptions" :range-key="'label'" :value="statusIndex" @change="handleStatusChange">
              <view class="picker-input">{{ statusOptions[statusIndex]?.label || '请选择' }}</view>
            </picker>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { store as uniIdPagesStore } from '@/uni_modules/uni-id-pages/common/store.js'
const loading = ref(true)
const recordId = ref('')

const statusOptions = [
  { label: '初诊', value: 0 },
  { label: '复诊', value: 1 },
  { label: '治疗中', value: 2 },
  { label: '已完成', value: 3 }
]

const formData = reactive({
  symptoms: '',
  diagnosis: '',
  treatment_plan: '',
  prescription: [],
  examination_results: [],
  images: [],
  assisting_nurses: [],
  status: 0,
  notes: ''
})

const originalData = reactive({
  patient_name: '',
  doctor_name: '',
  visit_date: null
})

const statusIndex = ref(0)
const nurseOptions = ref([])
const selectedNurses = ref([])
// 保存原始检查结果图片数据，避免使用blob URL
const originalExamImages = ref({}) // key: examIndex, value: 原始图片数组

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  recordId.value = currentPage.options.id || ''
  
  if (!recordId.value) {
    uni.showToast({ title: '缺少病例ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/medical_records/list' })
    }, 1500)
    return
  }
  
  await loadNurses()
  await loadRecordData()
  loading.value = false
})

// 加载护士列表
async function loadNurses() {
  try {
    const userQueryObj = uniCloud.importObject('dh-user-query')
    const result = await userQueryObj.listUsers({
      includeRoles: ['nurse', 'head_nurse'],
      format: 'with_role'
    })
    
    if (result.code === 200 && result.data) {
      nurseOptions.value = result.data
    }
  } catch (err) {
    console.error('加载护士列表失败:', err)
  }
}

function formatDate(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') return imageData
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

async function loadRecordData() {
  try {
    const dhMedicalRecords = uniCloud.importObject('dh-medical_records')
    const result = await dhMedicalRecords.getMedicalRecordById(recordId.value)
    
    if (result.code === 200 && result.data) {
      // 检查编辑权限（后端会进行权限检查，如果无权限会返回错误）
      // 这里只是加载数据，实际的权限检查在updateMedicalRecord时进行
      formData.symptoms = result.data.symptoms || ''
      formData.diagnosis = result.data.diagnosis || ''
      formData.treatment_plan = result.data.treatment_plan || ''
      formData.prescription = result.data.prescription || []
      formData.examination_results = result.data.examination_results || []
      formData.images = result.data.images || []
      formData.assisting_nurses = result.data.assisting_nurses || []
      formData.status = result.data.status || 0
      formData.notes = result.data.notes || ''
      
      // 存储只读的基本信息
      originalData.patient_name = result.data.patient_name || ''
      originalData.doctor_name = result.data.doctor_name || ''
      originalData.patient_id = result.data.patient_id || ''
      originalData.doctor_id = result.data.doctor_id || ''
      originalData.visit_date = result.data.visit_date
      
      // 保存原始检查结果图片数据，避免使用blob URL
      if (formData.examination_results && formData.examination_results.length > 0) {
        formData.examination_results.forEach((exam, index) => {
          if (exam.images && exam.images.length > 0) {
            // 保存原始图片数据
            originalExamImages.value[index] = [...exam.images]
            // 确保images字段存在且是数组
            if (!exam.images) {
              exam.images = []
            }
          } else {
            exam.images = []
          }
          // 初始化imageFileList为空数组
          exam.imageFileList = []
        })
      }
      
      // 设置界面显示
      statusIndex.value = statusOptions.findIndex(s => s.value === formData.status)
      if (statusIndex.value === -1) statusIndex.value = 0
      
      // 加载已选择的护士信息
      if (formData.assisting_nurses.length > 0) {
        const userQueryObj = uniCloud.importObject('dh-user-query')
        for (const nurseId of formData.assisting_nurses) {
          const nurseResult = await userQueryObj.getUser(nurseId, 'with_role')
          if (nurseResult.code === 200 && nurseResult.data) {
            selectedNurses.value.push(nurseResult.data)
          }
        }
      }
    } else {
      // 如果是权限错误，提示用户
      if (result.code === 403) {
        uni.showToast({ title: '无权编辑此病例', icon: 'none' })
      } else {
        throw new Error(result.message || '病例不存在')
      }
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/medical_records/list' })
      }, 1500)
      return
    }
  } catch (err) {
    console.error('加载病例数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/medical_records/list' })
    }, 1500)
  }
}

function handleStatusChange(e) {
  statusIndex.value = parseInt(e.detail.value)
  formData.status = statusOptions[statusIndex.value].value
}

function handleNurseSelect(e) {
  const index = parseInt(e.detail.value)
  const selectedNurse = nurseOptions.value[index]
  
  // 检查是否已经添加
  if (!selectedNurses.value.find(n => n._id === selectedNurse._id)) {
    selectedNurses.value.push(selectedNurse)
    formData.assisting_nurses.push(selectedNurse._id)
  }
}

function removeNurse(index) {
  selectedNurses.value.splice(index, 1)
  formData.assisting_nurses.splice(index, 1)
}

// 处方管理
function addPrescription() {
  formData.prescription.push({
    medicine_name: '',
    dosage: '',
    frequency: '',
    duration: ''
  })
}

function removePrescription(index) {
  formData.prescription.splice(index, 1)
}

// 检查结果管理
function addExam() {
  const newIndex = formData.examination_results.length
  formData.examination_results.push({
    exam_type: '',
    exam_result: '',
    exam_date: null,
    images: [],
    imageFileList: []
  })
  // 初始化原始图片数据
  originalExamImages.value[newIndex] = []
}

function removeExam(index) {
  formData.examination_results.splice(index, 1)
  // 删除对应的原始图片数据
  delete originalExamImages.value[index]
  // 重新索引原始图片数据
  const newOriginalExamImages = {}
  Object.keys(originalExamImages.value).forEach(key => {
    const oldIndex = parseInt(key)
    if (oldIndex < index) {
      newOriginalExamImages[oldIndex] = originalExamImages.value[oldIndex]
    } else if (oldIndex > index) {
      newOriginalExamImages[oldIndex - 1] = originalExamImages.value[oldIndex]
    }
  })
  originalExamImages.value = newOriginalExamImages
}

function removeExamImage(examIndex, imageIndex) {
  if (!formData.examination_results[examIndex].images) {
    formData.examination_results[examIndex].images = []
  }
  formData.examination_results[examIndex].images.splice(imageIndex, 1)
  // 同步更新原始图片数据
  if (originalExamImages.value[examIndex]) {
    originalExamImages.value[examIndex].splice(imageIndex, 1)
  }
}

function getExamDateStr(index) {
  const examDate = formData.examination_results[index]?.exam_date
  if (!examDate) return ''
  const date = new Date(examDate)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function handleExamDateChange(e, index) {
  formData.examination_results[index].exam_date = new Date(e.detail.value).getTime()
}

function handleExamImageSelect(e, index) {
  // uni-file-picker 的 @select 事件返回的 tempFiles 包含所有已选择的文件
  console.log('添加图片事件:', e)
  if (e.tempFiles) {
    // 过滤掉blob URL，只保留有效的文件对象
    const validFiles = e.tempFiles.filter(file => {
      // 如果是新选择的文件，应该有path属性
      // 如果是已存在的文件，应该有url属性且不是blob URL
      return file.path || (file.url && !file.url.startsWith('blob:'))
    })
    
    // 获取当前已有的文件列表
    const currentFiles = formData.examination_results[index].imageFileList || []
    
    // 将新选择的文件追加到现有列表中，避免覆盖
    formData.examination_results[index].imageFileList = [...currentFiles, ...validFiles]
    
    // 输出添加图片后的imageFileList数组
    console.log('添加图片后，检查项目', index, '的imageFileList:', formData.examination_results[index].imageFileList)
  }
}

function handleExamImageDelete(e, index) {
  // uni-file-picker 的 @delete 事件返回的是删除文件的信息，包含index, tempFile, tempFilePath
  console.log('删除图片事件:', e)
  console.log('删除图片前，检查项目', index, '的imageFileList:', formData.examination_results[index].imageFileList)
  
  // 从当前imageFileList中移除被删除的文件
  const currentFiles = formData.examination_results[index].imageFileList || []
  console.log('当前文件列表:', currentFiles)
  
  // 根据索引删除对应的文件
  if (e.index !== undefined && e.index >= 0 && e.index < currentFiles.length) {
    const newFiles = [...currentFiles]
    newFiles.splice(e.index, 1)
    
    // 过滤掉blob URL
    const validFiles = newFiles.filter(file => {
      return file.path || (file.url && !file.url.startsWith('blob:'))
    })
    
    formData.examination_results[index].imageFileList = validFiles
    console.log('删除图片后，检查项目', index, '的imageFileList:', formData.examination_results[index].imageFileList)
  } else {
    console.warn('无效的删除索引:', e.index)
    // 如果索引无效，则使用delete事件返回的tempFile进行匹配删除
    if (e.tempFile) {
      const newFiles = currentFiles.filter(file => {
        // 匹配文件的各种可能标识
        return !(file.uuid === e.tempFile.uuid || 
                file.name === e.tempFile.name || 
                file.cloudPath === e.tempFile.cloudPath ||
                file.url === e.tempFile.url ||
                (file.path && e.tempFilePath && file.path === e.tempFilePath))
      })
      
      // 过滤掉blob URL
      const validFiles = newFiles.filter(file => {
        return file.path || (file.url && !file.url.startsWith('blob:'))
      })
      
      formData.examination_results[index].imageFileList = validFiles
      console.log('通过文件匹配删除后，检查项目', index, '的imageFileList:', formData.examination_results[index].imageFileList)
    }
  }
}

// 获取检查结果图片文件列表，用于uni-file-picker显示
function getExamImageFileList(examIndex) {
  const exam = formData.examination_results[examIndex]
  if (!exam) return []
  
  // 返回imageFileList，如果不存在则返回空数组
  return exam.imageFileList || []
}

// 预览检查结果图片
function previewExamImage(images, currentImage, currentIndex = 0) {
  const imageUrls = images.map(img => getImageUrl(img)).filter(url => url && !url.startsWith('blob:'))
  const currentImageUrl = getImageUrl(currentImage)
  if (imageUrls.length === 0) {
    uni.showToast({ title: '没有可预览的图片', icon: 'none' })
    return
  }
  uni.previewImage({
    urls: imageUrls,
    current: currentImageUrl || imageUrls[currentIndex] || imageUrls[0]
  })
}

// 预览图片（用于其他场景）
function previewImage(url) {
  if (!url || url.startsWith('blob:')) return
  uni.previewImage({
    urls: [url],
    current: url
  })
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/medical_records/list' })
}

// 上传检查图像到云存储
async function uploadExamImagesToCloud(examIndex) {
  const examItem = formData.examination_results[examIndex]
  if (!examItem.imageFileList || examItem.imageFileList.length === 0) {
    return []
  }
  
  const uploadedImages = []
  for (const file of examItem.imageFileList) {
    try {
      // 如果已经有url且不是blob URL，说明已经上传过了，直接使用
      if (file.url && !file.url.startsWith('blob:')) {
        // 检查是否已经是完整的对象格式
        if (typeof file.url === 'object' && file.url !== null) {
          uploadedImages.push(file.url)
        } else {
          // 转换为标准格式对象
          uploadedImages.push({
            name: file.name || 'unnamed',
            extname: file.extname || (file.name ? file.name.split('.').pop() : 'jpg'),
            url: file.url
          })
        }
        continue
      }
      
      // 如果有path属性，说明是新选择的文件，需要上传
      if (file.path) {
        const uploadResult = await uniCloud.uploadFile({
          filePath: file.path,
          cloudPath: `medical_records/examinations/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.name ? file.name.split('.').pop() : 'jpg'}`
        })
        
        // 返回完整的对象格式，与医生添加页面保持一致
        uploadedImages.push({
          name: file.name || `image_${Date.now()}`,
          extname: file.name ? file.name.split('.').pop() : 'jpg',
          url: uploadResult.fileID,
          size: file.size || 0,
          file_id: uploadResult.fileID
        })
      }
    } catch (err) {
      console.error('上传检查图像失败:', err)
      throw err
    }
  }
  
  return uploadedImages
}

async function handleSubmit() {
  console.log('提交表单，当前所有检查项目的imageFileList:')
  formData.examination_results.forEach((exam, index) => {
    console.log(`检查项目 ${index}:`, exam.imageFileList)
  })
  
  // 检查必填字段 - 在编辑页面使用原始数据中的患者和医生ID
  if (!originalData.patient_id) {
    uni.showToast({ title: '患者信息缺失', icon: 'none' })
    return
  }
  
  if (!originalData.doctor_id) {
    uni.showToast({ title: '医生信息缺失', icon: 'none' })
    return
  }

  uni.showLoading({ title: '提交中...' })

  try {
    // 创建一个用于提交的数据副本
    const submitData = {
      ...formData,
      // 在编辑页面使用原始的患者和医生信息
      patient_name: originalData.patient_name,
      doctor_name: originalData.doctor_name,
      examination_results: formData.examination_results.map((exam, index) => {
        // 合并原始图片和新上传的图片
        const originalImages = originalExamImages.value[index] || []
        const newImages = exam.imageFileList || []
        
        // 输出当前检查项目的图片信息
        console.log(`提交时，检查项目 ${index} 的原始图片:`, originalImages)
        console.log(`提交时，检查项目 ${index} 的新图片:`, newImages)
        
        // 过滤出需要上传的新文件（有path属性）和已存在的文件（有url属性且不是blob URL）
        const filesToUpload = newImages.filter(file => {
          return file.path || (file.url && !file.url.startsWith('blob:'))
        })
        
        console.log(`提交时，检查项目 ${index} 需要上传的文件:`, filesToUpload)
        
        return {
          ...exam,
          images: [...originalImages, ...filesToUpload]
        }
      })
    }
    
    uni.showLoading({ title: '保存中...' })
    const dhMedicalRecords = uniCloud.importObject('dh-medical_records')
    const result = await dhMedicalRecords.updateMedicalRecord(recordId.value, submitData)
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/medical_records/list' })
      }, 1500)
    } else {
      // 如果是权限错误，给出明确提示
      if (result.code === 403) {
        uni.showToast({ title: '无权编辑此病例', icon: 'none' })
      } else {
        uni.showToast({ title: result.message || '更新失败', icon: 'none' })
      }
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    // 检查是否是权限错误
    if (err.message && err.message.includes('403')) {
      uni.showToast({ title: '无权编辑此病例', icon: 'none' })
    } else {
      uni.showToast({ title: err.message || '更新失败', icon: 'none' })
    }
  }
}
</script>

<style lang="scss" scoped>
.record-edit-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-content {
  flex: 1;
  padding: 20rpx;
}

.form-card {
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 20rpx;
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-subtitle {
  font-size: 24rpx;
  color: #999;
  margin-left: 12rpx;
}

.card-body {
  padding: 32rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #333;
  min-width: 180rpx;
}

.input {
  flex: 1;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker-input {
  flex: 1;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  color: #333;
}

.textarea-wrapper {
  width: 100%;
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  box-sizing: border-box;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
}

.nurse-selector {
  flex: 1;
}

.selected-nurses {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.nurse-tag {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background: #e3f2fd;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.nurse-name {
  color: #1976d2;
}

.remove-btn {
  font-size: 32rpx;
  color: #1976d2;
  font-weight: bold;
  cursor: pointer;
  line-height: 1;
}

.prescription-item,
.exam-item {
  padding: 24rpx;
  background: #f9fafb;
  border-radius: 8rpx;
  margin-bottom: 16rpx;
  border: 1rpx solid #e0e0e0;
}

.prescription-header,
.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx dashed #d0d0d0;
}

.prescription-title,
.exam-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.btn-add {
  width: 100%;
  padding: 20rpx;
  background: #f0f7ff;
  color: #1976d2;
  border: 1rpx dashed #1976d2;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
  margin-top: 16rpx;
}

.image-preview-wrapper {
  width: 100%;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.image-item {
  width: 100%;
  padding-bottom: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  z-index: 10;
}

.image-upload-section {
  margin-top: 20rpx;
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 12rpx;
}
</style>

